package com.yao.longhan.utils;

import android.os.Environment;
import android.util.Log;

import com.yao.longhan.BuildConfig;
import com.yao.longhan.listener.ProgressResponseListener;
import com.yao.longhan.net.DownloadProgressInterceptor;
import com.yao.longhan.net.RetrofitService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by heyao on 2017/7/24.
 */

public class ApkDownloadManager {

    private static String TAG = "ApkDownloadManager";
    private static RetrofitService retrofitService;

    public static void downloadApk(RetrofitService retrofitService) {
        retrofitService.downloadAPK("apk/download").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    final ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
                                    return;
                                FileOutputStream fileOutputStream = null;
                                InputStream inputStream = null;
                                try {
                                    File file = new File(Environment.getExternalStorageDirectory(), "/SkyBay/download/");
                                    if (!file.exists()) file.mkdirs();
                                    File downloadFile = new File(file, "VIPSOUQ.apk");

                                    fileOutputStream = new FileOutputStream(downloadFile);
                                    inputStream = responseBody.byteStream();
                                    byte[] buffer = new byte[1024];
                                    int i;
                                    while ((i = inputStream.read(buffer)) != -1) {
                                        fileOutputStream.write(buffer, 0, i);
                                    }
                                    fileOutputStream.flush();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } finally {
                                    if (fileOutputStream != null) {
                                        try {
                                            fileOutputStream.close();
                                        } catch (IOException e) {
                                        }
                                    }
                                    if (inputStream != null) {
                                        try {
                                            inputStream.close();
                                        } catch (IOException e) {
                                        }
                                    }
                                }
                            }
                        }.start();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
            }
        });
    }

    public static void download(ProgressResponseListener listener) {
        if (retrofitService == null) {
            synchronized (ApkDownloadManager.class) {
                if (retrofitService == null) {
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    builder.writeTimeout(30, TimeUnit.SECONDS);
                    builder.readTimeout(30, TimeUnit.SECONDS);
                    builder.connectTimeout(30, TimeUnit.SECONDS);
                    builder.addInterceptor(new DownloadProgressInterceptor(listener));

                    if (BuildConfig.DEBUG) {
                        builder.addInterceptor(new HttpLoggingInterceptor());
                    }

                    Retrofit.Builder reBuilder = new Retrofit.Builder();
                    reBuilder.client(builder.build());
                    reBuilder.baseUrl(BuildConfig.BASE_URL);
                    Retrofit retrofit = reBuilder.build();
                    retrofitService = retrofit.create(RetrofitService.class);
                }
            }
        }
        downloadApk(retrofitService);
    }
}
